import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../widgets/gradient_background.dart';
import '../widgets/app_button.dart';
import 'package:permission_handler/permission_handler.dart';

class PhotoDivinationPage extends StatefulWidget {
  const PhotoDivinationPage({Key? key}) : super(key: key);

  @override
  State<PhotoDivinationPage> createState() => _PhotoDivinationPageState();
}

class _PhotoDivinationPageState extends State<PhotoDivinationPage> {
  bool _isProcessing = false;
  XFile? _capturedImage;
  final ImagePicker _picker = ImagePicker();
  
  Future<void> _takePicture() async {
    // 检查相机权限
    final status = await Permission.camera.request();
    if (status != PermissionStatus.granted) {
      // 显示权限请求对话框
      _showPermissionDialog();
      return;
    }
    
    setState(() {
      _isProcessing = true;
    });
    
    try {
      // 调用相机拍照
      final XFile? photo = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 80,
      );
      
      if (photo != null) {
        setState(() {
          _capturedImage = photo;
        });
        
        // 跳转到结果页面
        Navigator.pushNamed(
          context,
          '/divination-result',
          arguments: {
            'type': 'photo',
            'imagePath': photo.path,
          },
        );
      }
    } catch (e) {
      print('拍照失败: $e');
      // 显示错误提示
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('拍照失败，请重试')),
      );
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }
  
  // 显示权限请求对话框
  void _showPermissionDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('需要权限'),
        content: const Text('拍照起卦功能需要相机权限，请在设置中允许访问相机。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              openAppSettings();
            },
            child: const Text('去设置'),
          ),
        ],
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GradientBackground(
        child: SafeArea(
          child: Column(
            children: [
              // 顶部栏
              Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 20,
                  vertical: 15,
                ),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () => Navigator.pop(context),
                      child: const Text(
                        '←',
                        style: TextStyle(
                          fontSize: 24,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Center(
                        child: Text(
                          '拍照起卦',
                          style: Theme.of(context).textTheme.displayMedium,
                        ),
                      ),
                    ),
                    const SizedBox(width: 24),
                  ],
                ),
              ),
              
              // 主体内容
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                        children: [
                          const SizedBox(height: 32),
                          Text(
                            '拍照起卦',
                            style: Theme.of(context).textTheme.displayLarge,
                          ),
                          const SizedBox(height: 16),
                          Text(
                            '拍摄任意物体，AI将识别其属性生成卦象。',
                            style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                              color: Colors.black.withOpacity(0.7),
                            ),
                          ),
                          const SizedBox(height: 32),
                          
                          // 相机预览区域
                          ClipRRect(
                            borderRadius: BorderRadius.circular(24),
                            child: Container(
                              height: 300,
                              width: double.infinity,
                              decoration: BoxDecoration(
                                color: Colors.black.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(24),
                              ),
                              child: Stack(
                                alignment: Alignment.center,
                                children: [
                                  // 在实际应用中，这里会显示相机预览
                                  // 这里使用模拟的背景图片
                                  Opacity(
                                    opacity: 0.7,
                                    child: Image.network(
                                      'https://picsum.photos/id/1018/375/812',
                                      width: double.infinity,
                                      height: double.infinity,
                                      fit: BoxFit.cover,
                                      errorBuilder: (context, error, stackTrace) {
                                        return Container(
                                          color: Colors.grey.shade200,
                                          child: const Center(
                                            child: Icon(
                                              Icons.image_not_supported,
                                              size: 50,
                                              color: Colors.grey,
                                            ),
                                          ),
                                        );
                                      },
                                    ),
                                  ),
                                  
                                  // 相机提示
                                  Container(
                                    padding: const EdgeInsets.all(20),
                                    decoration: BoxDecoration(
                                      color: Colors.white.withOpacity(0.8),
                                      borderRadius: BorderRadius.circular(16),
                                    ),
                                    child: Column(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        const Text(
                                          '📸',
                                          style: TextStyle(fontSize: 48),
                                        ),
                                        const SizedBox(height: 12),
                                        Text(
                                          '轻触屏幕，开始拍照',
                                          style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                                            color: Colors.black.withOpacity(0.7),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                      
                      // 底部按钮
                      Column(
                        children: [
                          AppPrimaryButton(
                            text: _isProcessing ? '处理中...' : '拍照',
                            onPressed: _isProcessing ? null : _takePicture,
                          ),
                          const SizedBox(height: 16),
                          AppSecondaryButton(
                            text: '取消',
                            onPressed: () => Navigator.pop(context),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}